<!--
 * @Descripttion: 新增盘点单
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-12 15:32:55
 -->
<template>
  <div class="bill_container">
    <affix>
      <div class="clearfix paddingLR20">
        <div class="oper-button btn-group fl">
          <SelectGoodsBtns
            :btns="['barcode']"
            @on-select-sure="onSelectGoodsSure"
          />
        </div>
        <div class="oper-button btn-group fr">
          <el-button type="default" @click="btnJump2List">历史单据</el-button>
          <el-button type="primary" :loading="btnLoading.save" @click="btnSave">保存(Ctrl+S)</el-button>
        </div>
      </div>
    </affix>
    <el-main>
      <el-form
        ref="billForm"
        :model="dataObj"
        :rules="ruleValidator"
        label-position="left"
        inline
        label-width="80px"
      >
        <el-card shadow="never">
          <div slot="header" class="header clearfix">
            <div class="clearfix index_container form">
              <div class="fr">
                <el-form-item class="bill-number white-border" label="单据编号: " prop="billNo">
                  <el-input v-model="dataObj.billNo" class="w150" size="mini" />
                </el-form-item>
              </div>
            </div>
            <div class="index_container title">
              <h1> 商品盘点单 </h1>
            </div>
          </div>
          <div class="clearfix">
            <div class="fl">
              <!-- <el-checkbox v-model="dataObj.isPrint" label="保存后打印" border /> -->
            </div>
            <div class="fr">
              <el-form-item label="经手人:" prop="handUserId">
                <select-employee
                  v-model="dataObj.handUserId"
                  :is-set-default="true"
                />
              </el-form-item>
              <el-form-item label="业务日期:">
                <el-date-picker v-model="dataObj.businessTime" class="w150" type="datetime" />
              </el-form-item>
            </div>
          </div>
          <goods-select
            ref="GoodsSelect"
            :is-set-price="false"
          />
          <div class="bottom">
            <table class="table" border="1" cellspacing="0" cellpadding="0">
              <tr>
                <td style="padding:0;" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <table class="wfull" border="0" cellspacing="0" cellpadding="0">
                    <tr class="lastrow">
                      <td width="100">
                        备 注:
                      </td>
                      <td class="lastCol">
                        <el-input v-model="dataObj.remarks" class="wfull" type="textarea" />
                      </td>
                    </tr>
                  </table>
                </td>
                <td :width="tableFixedWidth" style="padding:0; position: relative; overflow: hidden;">
                  <el-button class="full-button" type="primary" :loading="btnLoading.save" @click="btnSave">保存(Ctrl+S)</el-button>
                </td>
              </tr>
            </table>
          </div>
        </el-card>
      </el-form>
    </el-main>
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import { addInventory } from '@/api/bill/bill-inventory.js'
import { amount } from '@/libs/tools.js'
import { add, update, jump2pages } from './mixins'
import GoodsSelect from './components/goods-select'
import SelectEmployee from '@/views/components/SelectEmployee'
import SelectGoodsBtns from '@/views/components/SelectGoodsBtns'
import { columns } from './mixins'
import Affix from '@/components/Affix'
import moment from 'moment'
import clonedeep from 'clonedeep'

export default {
  name: 'CheckstockAdd',
  components: { SelectGoodsBtns, SelectEmployee, GoodsSelect, Affix },
  filters: {
    goodAmount: function(row) {
      return amount(row.price).multiply(row.num).format()
    }
  },
  mixins: [add, update, columns, oftenuse, jump2pages],
  props: {
    billId: {
      type: String,
      default: null
    },
    operation: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      isShowQrcode: false,
      ruleValidator: {
        amountPaid: [
          { validator: (rule, value, callback) => {
            const amountPayable = this.dataObj.amountPayable
            if (value > amountPayable) return callback(new Error(`金额不能大于${amountPayable}`))
            callback()
          } }
        ]
      },
      tableFixedWidth: 300,
      goodsSelectComp: null
    }
  },
  computed: {
    totalMsg: function() {
      const GoodsSelect = this.goodsSelectComp
      if (!GoodsSelect) return {}
      return GoodsSelect.totalMsg
    }
  },
  watch: {
    'totalMsg': {
      handler(data) {
        const price = data.price || '0.00'
        this.$set(this.dataObj, 'amountPayable', price)
        this.$set(this.dataObj, 'amountPaid', price)
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.goodsSelectComp = this.$refs.GoodsSelect
  },
  created() {
    this.initData()
  },
  methods: {
    btnJump2List() {
      this.jump2List()
    },
    btnSave() {
      this.handleVali().then(_ => {
        const billDetailList = this.formatReqData(clonedeep(this.$refs.GoodsSelect.getPostData()))
        const bill = clonedeep(this.dataObj)
        if (billDetailList.length === 0) return this.$message.error('请选择盘点商品！')
        const params = { bill, billDetailExtInventoryList: billDetailList }
        this.setBtnLoading('save', true)
        this.saveData(params).then((res) => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) return
          this.jump2List()
        }).catch(err => {
          console.log(err)
          this.setBtnLoading('save', false)
        })
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // api
    jump2List() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'CheckstockList',
        params: { refresh: true }
      })
    },
    doStoreLock(data) {
      const params = [
        { id: data.id, isLock: '1' }
      ]
    },
    cancleStoreLock() {
    },
    popStoreMsg(data) {
      this.$confirm('锁定后才可以进行盘点操作，是否锁定?', '提示', {
        confirmButtonText: '快速锁定',
        cancelButtonText: '暂不盘点',
        type: 'warning'
      }).then(() => {
        this.doStoreLock(data)
      }).catch(() => {
        this.cancleStoreLock()
      })
    },
    handleVali() {
      const v1 = this.handleValid('billForm')
      const v2 = this.$refs.GoodsSelect.valiData()
      return Promise.all([v1, v2])
    },
    /**
     * 把商品数据转化成票据商品详情的数据
     */
    formatGoodsData2OrderDetail(tableData) {
      tableData.forEach(item => {
        item.goodsId = item.id
        item.price = item.purchasingPrice
      })
      return tableData
    },
    initData() {
      if (this.operation === 'add') this.initSaveData()
      if (['update', 'view'].indexOf(this.operation) !== -1) this.initUpdateData()
      if (this.operation === 'copyadd') {
        this.initCopyData().then(_ => {
          this.getBillCode()
          const date = moment().format('YYYY-MM-DD HH:mm:ss')
          this.$set(this.dataObj, 'businessTime', date)
        })
      }
    },
    /**
     * 保存盘点订单
     */
    saveData(params) {
      return new Promise((resolve, reject) => {
        addInventory(params).then(res => {
          resolve(res)
          if (res.data.flag) return this.$notify.success({ title: '保存成功！' })
          this.$notify.error({ title: '保存失败！', message: res.data.message || '' })
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err || '' })
          reject(err)
        })
      })
    },
    /**
     * 重置数据
     */
    resetData() {
      this.initSaveData()
    },
    formatReqData(listData) {
      listData.forEach(item => {
        const { realQuantity, quantity } = item
        item.changeQuantity = Math.abs(realQuantity - quantity)
        item.direction = realQuantity > quantity ? '1' : '0'
        //
        const options = item.options || { unit: [], price: [] }
        item.options = typeof options === 'string' ? options : JSON.stringify(options)
      })
      return listData
    },
    // on
    onTdMouseEnter(e) {
      const target = e.target
      target.className = 'bg-gay'
    },
    onTdMouseLeave(e) {
      const target = e.target
      target.className = ''
    },
    onSelectGoodsSure(data) {
      // 合格组
      const qualified = []
      // 不合格
      const disQualified = []
      const tableData = this.$refs.GoodsSelect.getTableData()
      const skuIds = tableData.map(item => { return item.skuId })
      data.forEach(item => {
        const quantity = item.originQuantity + item.quantityIn - item.quantityOut
        item.bookQty = quantity
        item.realQty = quantity
        if (skuIds.indexOf(item.skuId) !== -1) {
          disQualified.push(item)
        } else {
          qualified.push(item)
        }
      })
      if (disQualified.length > 0) {
        const disNames = disQualified.map(item => { return item.name })
        this.$message.error(`商品 [${disNames.toString()}] 已选，不能重复选择!`)
      }
      this.$refs.GoodsSelect.pushTableData(qualified)
    }
  }
}
</script>
